package com.warmlight.voicepacket.web;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.BaseActivity;

public class WebViewActivity extends BaseActivity implements View.OnClickListener {

    private String mUrl;
    private String title;

    private FrameLayout mLayout;
    private ProgressBar mSeekBar;
    private Html5WebView mWebView;

    public static void loadUrl(Context context,String url,String title){
        Intent intent = new Intent(context,WebViewActivity.class);
        intent.putExtra("url",url);
        intent.putExtra("title",title);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_web);

        getParameter();

        mLayout = (FrameLayout) findViewById(R.id.web_layout);
        mSeekBar = (ProgressBar) findViewById(R.id.web_sbr);
        LinearLayout ll_back = (LinearLayout) findViewById(R.id.ll_back);
        TextView tv_header_titlename = (TextView) findViewById(R.id.tv_header_titlename);
        if (TextUtils.isEmpty(title)){
            tv_header_titlename.setText("玩皮语音包");

        }else {
            tv_header_titlename.setText(title);
        }
        ll_back.setOnClickListener(this);
        // 创建 WebView
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView = new Html5WebView(getApplicationContext());
        mWebView.setLayoutParams(params);
        mLayout.addView(mWebView);
        mWebView.setWebChromeClient(new Html5WebChromeClient());
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.loadUrl(mUrl);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                if (mWebView != null && mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    WebViewActivity.this.finish();
                }
                break;
        }
    }

    class MyWebViewClient extends Html5WebView.BaseWebViewClient{
        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            mSeekBar.setProgress(0);
            mSeekBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            mSeekBar.setVisibility(View.INVISIBLE);
//                writeData();
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {

        }

        /**
         * 防止加载网页时调起系统浏览器
         */
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    // 继承 WebView 里面实现的基类
    class Html5WebChromeClient extends Html5WebView.BaseWebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            // 顶部显示网页加载进度
            mSeekBar.setProgress(newProgress);
            if (newProgress == 100){
                mSeekBar.setVisibility(View.GONE);
            }
        }

    }

    @Override
    protected void onDestroy() {
        // 销毁 WebView
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    public void getParameter() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mUrl = bundle.getString("url");
            title = bundle.getString("title");
        } else {
            mUrl = "https://wing-li.github.io/";
            title = "玩皮语音包";
        }
    }

    //============================= 下面是本 demo  的逻辑代码
    // ======================================================================================

    /**
     * 按目录键，弹出“关闭页面”的选项
     */
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu, menu);
//        return super.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//
//        int itemId = item.getItemId();
//        switch (itemId) {
//            case R.id.close:
//                WebViewActivity.this.finish();
//                return true;
//            case R.id.copy:
//                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
//                String url = mWebView.getUrl();
//                ClipData clipData = ClipData.newPlainText("test", url);
//                if (clipboardManager != null) {
//                    clipboardManager.setPrimaryClip(clipData);
//                    Toast.makeText(getApplicationContext(), "本页网址复制成功", Toast.LENGTH_SHORT).show();
//                }
//                return true;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    private long mOldTime;

    /**
     * 点击“返回键”，返回上一层
     * 双击“返回键”，返回到最开始进来时的网页
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (System.currentTimeMillis() - mOldTime < 1500) {
//                mWebView.clearHistory();
//                mWebView.loadUrl(mUrl);
//            } else
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                WebViewActivity.this.finish();
            }
//            mOldTime = System.currentTimeMillis();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}
